package cn.edu.scau.cmi.mengzhuorong.hibernate.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Example;

import cn.edu.scau.cmi.mengzhuorong.hibernate.domain.Student;
import cn.edu.scau.cmi.mengzhuorong.hibernate.util.HibernateSessionFactoryUtil;

public class StudentDAO {
public static final String NAME = "name";
	
	private Session session;
	
	public void save(Student transientInstance) {
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	private Session getSession() {
		// TODO Auto-generated method stub
		session=HibernateSessionFactoryUtil.getSession();
		return session;
	}
	
	public void delete(Student student ) {
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
        s.beginTransaction();
		s.delete(student);
		s.getTransaction().commit();
	    s.close();
	    sf.close();
	}
	
	public Student findById(Long id) {
		Student student = (Student) getSession().get(Student.class, id);
		return student;
	}
	
	public List findByExample(Student instance) {
		List results = getSession().createCriteria("cn.edu.scau.cmi.mengzhuorong.hibernate.Student")
				.add(Example.create(instance)).list();
		return results;
	}
	
	public List findByProperty(String propertyName, Object value) {
		String queryString = "from Student as model where model." + propertyName + "= ?";
		Query queryObject = getSession().createQuery(queryString);
		queryObject.setParameter(0, value);
		return queryObject.list();
	}
	
	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}
	
	public List findAll() {
		String queryString = "from Student";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}
	
	public void update(Student student) {
		
		SessionFactory sf = new Configuration().configure().buildSessionFactory(); 
        Session s = sf.openSession();
        s.beginTransaction();
        s.update(student);
        s.getTransaction().commit();
        s.close();
        sf.close();
	}
}
